/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-07 09:26:03
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-21 10:57:02
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/device_detail/pv_inverter_detail/pv_inverter_detail_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';

import 'package:get/get.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import 'pv_inverter_detail_model.dart';

class PvInverterDetailController extends BaseDetailController {
  PvInverterDetailModel model = PvInverterDetailModel();

  DeviceServices deviceServices = DeviceServices();

  String title = '';

  late int deviceId;

  int? productId;

  StreamSubscription? _subscript;

  Map<String, dynamic>? dataSource;

  UseSubsribe subsribe = UseSubsribe();

  List<CurrentType> inputDatas = [];
  List<CurrentType> outputDatas = [];
  // 日发电量的物模型Key
  String dayCapKey = 'dayCap';
  // 日发电量的物模型
  Map? dayCapProperty;

  @override
  void onInit() {
    super.onInit();
    deviceId = Get.arguments['deviceId'];
    title = Get.arguments['deviceName'];

    productId = Get.arguments['productId'];

    inputDatas = List.generate(
        12,
        (index) => CurrentType(
            groupName: 'PV${index + 1}', voltage: null, current: null));

    outputDatas = List.generate(
      3,
      (index) => CurrentType(
          groupName: ['A', 'B', 'C'][index], voltage: null, current: null),
    );

    _subscript = subsribe.start([deviceId], true).stream.listen((data) {
          Log.d('subsribe====$data');
          for (var i = 0; i < inputDatas.length; i++) {
            inputDatas[i]
              ..voltage = data['Upv${i + 1}']
              ..current = data['Ipv${i + 1}'];
          }
          for (var i = 0; i < PvInverterDetailModel.outputColoums.length; i++) {
            outputDatas[i]
              ..voltage = data['U${['a', 'b', 'c'][i]}']
              ..current = data['I${['a', 'b', 'c'][i]}'];
          }
          for (var i = 0; i < model.propertyList.length; i++) {
            model.propertyList[i]['value'] =
                data[model.propertyList[i]['id']] ??
                    model.propertyList[i]['value'];
          }
          update();
        });

    if (productId != null) {
      getDeviceProperties();
    }
  }

  getDeviceProperties() => Configs.httpClient.requestWithLoading(() async {
        try {
          var data =
              await deviceServices.getDeviceProperty({'productId': productId});

          List properties = data['properties'];

          model.propertyList =
              model.propertyList.map<Map<String, dynamic>>((e) {
            var property = properties
                .firstWhereOrNull((element) => element['id'] == e['id']);
            if (property != null) {
              e['dataType'] = property['dataType'];
            }
            return e;
          }).toList();

          dayCapProperty =
              properties.firstWhere((element) => element['id'] == dayCapKey);
          update();
        } catch (e) {
          Log.d(e.toString());
        }
      });

  @override
  void onReady() {}

  @override
  void onClose() {
    _subscript?.cancel();
    subsribe.closeListen();
  }
}
